package com.lovo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import com.lovo.result.UserValid;
import com.lovo.service.IUserService;
import com.lovo.utill.JWTUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/users")
@ResponseResult
public class UserController {

    @Resource
    private IUserService userInfoService;
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public Object login(String userName, String userPass) throws GlobalHandleException {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name", userName);
        wrapper.eq("user_pwd", userPass);
        UserBean userInfoBean = userInfoService.getOne(wrapper);
        if (userInfoBean == null) {
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }

//        session.setAttribute("user",userInfoBean);
        String token = JWTUtil.createToken(userInfoBean.getUserName(), userInfoBean.getUserPwd(), Calendar.MINUTE, 30);
        String refreshToken = JWTUtil.createToken(userInfoBean.getUserName().toString(), userInfoBean.getUserPwd(), Calendar.DATE, 7);
        Map map = new HashMap();
        map.put("token", token);
        map.put("refreshToken", refreshToken);
        return map;
    }

    /**
     * 从token中获取用户对象
     * @return
     */
    @GetMapping("/token")
    @UserValid
    public Object getUserWithToken(HttpServletRequest request){
        return SecurityUtils.getSubject().getPrincipal();
    }

    @GetMapping("/refreshToken")
    @UserValid
    public Object refreshToken(HttpServletRequest request) {
        UserBean userInfoBean = (UserBean) request.getAttribute("user");
        return JWTUtil.createToken(userInfoBean.getUserId().toString(), userInfoBean.getUserPwd(), Calendar.SECOND, 10);
    }

}

